﻿using Quartz;
using Quartz.Impl;
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ProcessStartRestart_win
{
    public partial class mainForm : Form
    {
        private bool isStart = false;

        public mainForm()
        {
            InitializeComponent();
        }

        private void mainForm_Load(object sender, EventArgs e)
        {
            startCheckBox.Enabled = false;
            textBox1.Text = "ztbWin";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var t = Run(Convert.ToInt32(numericUpDown1.Value));
            if(t.Status == TaskStatus.RanToCompletion) isStart = true ;

            if (isStart)
            {
                textBox1.Enabled = false;
                numericUpDown1.Enabled = false;
                closeCheckBox.Enabled = false;
                startCheckBox.Enabled = false;
                button1.Enabled = false;
            }
        }

        /// <summary>
        /// 任务调度的使用过程
        /// </summary>
        /// <param name="timer"></param>
        /// <returns></returns>
        public async Task Run(int timer)
        {
            // 1.创建scheduler的引用
            ISchedulerFactory schedFact = new StdSchedulerFactory();
            IScheduler sched = await schedFact.GetScheduler();

            //2.启动 scheduler
            await sched.Start();

            // 3.创建 job
            IJobDetail job = JobBuilder.Create<SimpleJob>()
                    .WithIdentity("job1", "group1")
                    .UsingJobData("close", closeCheckBox.Checked)
                    .UsingJobData("start", startCheckBox.Checked )
                    .UsingJobData("name", textBox1.Text)
                    .Build();

            // 4.创建 trigger
            ITrigger trigger = TriggerBuilder.Create()
                .WithIdentity("trigger1", "group1")
                .WithSimpleSchedule(x => x.WithIntervalInHours(timer).RepeatForever())
                .Build();

            // 5.使用trigger规划执行任务job
            await sched.ScheduleJob(job, trigger);
        }
    }

    /// <summary>
    /// 任务
    /// </summary>
    public class SimpleJob : IJob
    {
        public virtual Task Execute(IJobExecutionContext context)
        {
            var jobMap = context.JobDetail.JobDataMap;

            bool close = jobMap.GetBoolean("close");
            bool start = jobMap.GetBoolean("start");
            string name = jobMap.GetString("name");

            if (close) Kill(name);
            Thread.Sleep(1000);
            if (start) Start(name);

            return Console.Out.WriteLineAsync($"完成任务 在{DateTime.Now}");
        }


        private void Kill(string name) {
            Process[] processs = Process.GetProcesses();
            foreach (var prItem in processs) {
                if (name == prItem.ProcessName) {
                    prItem.Kill();
                }
            }
        }

        private void Start(string name) {

        }

    }
}
